package yxy.apple.util.concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/** */
public final class RunnableStatsManager {

	private static final Map<Class<?>, ClassStat> classStats = new HashMap<Class<?>, ClassStat>();

	private static final class ClassStat {
		private final String className;
		private final MethodStat runnableStat;

		private ClassStat(Class<?> clazz) {
			className = clazz.getName().replace("com.tjyouai.gameserver.", "");
			runnableStat = new MethodStat(className, "run()");

			classStats.put(clazz, this);
		}

		private MethodStat getRunnableStat() {
			return runnableStat;
		}
	}

	private static final class MethodStat {
		private final ReentrantLock lock = new ReentrantLock();

		private long min = Long.MAX_VALUE;
		private long max = Long.MIN_VALUE;

		private MethodStat(String className, String methodName) {
		}

		private void handleStats(long runTime) {
			lock.lock();
			try {
				min = Math.min(min, runTime);
				max = Math.max(max, runTime);
			} finally {
				lock.unlock();
			}
		}
	}

	private static ClassStat getClassStat(Class<?> clazz, boolean synchronizedAlready) {
		ClassStat classStat = classStats.get(clazz);

		if (classStat != null) {
			return classStat;
		}
		if (!synchronizedAlready) {
			synchronized (RunnableStatsManager.class) {
				return getClassStat(clazz, true);
			}
		}

		return new ClassStat(clazz);
	}

	public static void handleStats(Class<? extends Runnable> clazz, long runTime) {
		getClassStat(clazz, false).getRunnableStat().handleStats(runTime);
	}

}
